package com.kaifamiao.tcp;

import java.io.*;
import java.net.*;
import java.nio.file.*;

public class Receiver {
    public static void main(String[] args) throws IOException {
        final ServerSocket serverSocket = new ServerSocket(8080);
        final Path outputPath = Paths.get("/Users/linrui/b");

        while (true) {
            final Socket clientSocket = serverSocket.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try (DataInputStream dis = new DataInputStream(clientSocket.getInputStream())) {
                        String command = dis.readUTF();
                        Path filePath = outputPath.resolve(dis.readUTF());  // use the relative path
                        if ("ADD".equals(command)) {
                            if (dis.readBoolean()) {
                                Files.createDirectories(filePath);
                            } else {
                                receiveFile(clientSocket, filePath);
                            }
                        } else if ("DELETE".equals(command)) {
                            Files.deleteIfExists(filePath);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            clientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                private void receiveFile(Socket socket, Path outputPath) throws IOException {
                    byte[] buffer = new byte[4096];
                    try (DataInputStream dis = new DataInputStream(socket.getInputStream());
                         FileOutputStream fos = new FileOutputStream(outputPath.toFile())) {

                        long fileSize = dis.readLong();
                        int bytesRead;
                        while (fileSize > 0 && (bytesRead = dis.read(buffer, 0, (int) Math.min(buffer.length, fileSize))) != -1) {
                            fos.write(buffer, 0, bytesRead);
                            fileSize -= bytesRead;
                        }
                    }
                }
            }).start();
        }
    }
}
